package com.bci.pwtz.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.ConfigMapper;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.Kzsxsbzp;
import com.bci.pwtz.service.KzsxsbzpService;
import com.bci.pwtz.service.PictureUploadAndDownloadService;

@Controller
@RequestMapping("/user/picture")
public class PictureUploadController extends AbstractController
{
@Autowired
private PictureUploadAndDownloadService service;
@Autowired
private ConfigMapper objMapper;
@Autowired
private KzsxsbzpService kService;
private static List<Kzsxsbzp> newklist=new ArrayList<Kzsxsbzp>();

@RequestMapping("/upload")
@ResponseBody
public void upload(HttpServletRequest request,HttpServletResponse response, MultipartFile picfile,String devicename,String pictype,int imgcount){
    String prefix = "";
    String fileName = "";
    String newFileName = "";
    String url = "";
    String savePath = "";
    if(PwtzConstants.THE_SERVER_TYPE==1){
        savePath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
    }else{
        savePath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
        savePath = savePath.replaceAll("\\\\", "/");    //本地
    }
//  savePath = savePath.replaceAll("/", "\\\\");    //服务器
    fileName = picfile.getOriginalFilename();
    prefix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
    try
    {
        request.setCharacterEncoding("UTF-8");
        /*String imgcount=request.getParameter("imgcount");
        String pictype=request.getParameter("pictype");
        String devicename=request.getParameter("devicename");*/
        newFileName = devicename + pictype+imgcount;
        String picname=System.currentTimeMillis()+prefix;
        url = savePath +picname;
        BufferedInputStream in = new BufferedInputStream(picfile.getInputStream());
        File file = new File(savePath);
        if  (!file .exists()  && !file .isDirectory())      
        {       
            file .mkdir();    
        }
        FileOutputStream out;
        out = new FileOutputStream(new File(url));
        BufferedOutputStream output = new BufferedOutputStream(out);
        Streams.copy(in, output, true);
        writeJsonObject(
                request,
                response,
                "{msgDesc:\"上传成功\" ,msg:\""+newFileName+"\",resourcepicname:\""+picname+"\",opResult:\"0\"}");
    }
    catch (FileNotFoundException e)
    {
        writeJsonObject(
                request,
                response,
                "{msgDesc:\"上传失败\",msg:\""+e+"\",opResult:\"1\"}");
        e.printStackTrace();
    }
    catch (IOException e)
    {
        writeJsonObject(
                request,
                response,
                "{msgDesc:\"上传失败\" ,msg:\""+e+"\",opResult:\"2\"}");
        e.printStackTrace();
    }
}

@RequestMapping("/add")
@ResponseBody
public void add(String picname,String resourcepicname,String linecode,String devicename,String deviceid,int devicetype){
    String prefix = "";
//    String fileName = "";
    String newFileName = "";
    String pictype = "";
    int indexnumber=0;
    String resourcePath = "";
    if(PwtzConstants.THE_SERVER_TYPE==1){
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
    }else{
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
        resourcePath = resourcePath.replaceAll("\\\\", "/");    //本地
    }
    String remotePath="";
    //String savePath="D:/upload/";
    //savePath = savePath.replaceAll("\\\\", "/");  //本地测试
    //resourcePath = resourcePath.replaceAll("/", "\\\\");    //服务器
//    resourcePath = resourcePath.replaceAll("\\\\", "/");    //本地测试
    try
    {
        Kzsxsbzp k=new Kzsxsbzp();
        picname=java.net.URLDecoder.decode(picname,"UTF-8");
        resourcePath=resourcePath+resourcepicname;
        prefix=resourcepicname.substring(resourcepicname.indexOf("."));
//        fileName=picname.substring(0,picname.indexOf("."));
        indexnumber=PwtzUtils.passInt(picname.substring(picname.length()-1));
        pictype=picname.substring(devicename.length(),picname.length()-1);
        CompanyUser user=(CompanyUser) request.getSession().getAttribute("user");
        Long companyId=user.getLastCompanyId();
//        remotePath=objMapper.selectByKey("DevicePICPath").get(0).getConfigValue();
//        remotePath=remotePath.replaceAll("@COMPANYID", companyId.toString());
        newFileName=picname+"_"+resourcepicname;
        if(PwtzConstants.THE_SERVER_TYPE==1){
            remotePath=request.getSession().getServletContext().getRealPath("/")+"\\Attachment\\"+companyId+"\\DevicePIC\\";
        }else{
            remotePath=request.getSession().getServletContext().getRealPath("/")+"/Attachment/"+companyId+"/DevicePIC/";
        }
        FileInputStream is=null;
        FileOutputStream os=null;
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        File resourcefile=new File(resourcePath);
        if(!resourcefile.exists()){
            return;
        }
        File file=new File(remotePath);
        if(!file.exists()){
            file.mkdirs();
        }
        file=new File(remotePath+resourcepicname);
        try
        {
            is=new FileInputStream(resourcefile);
            bis=new BufferedInputStream(is);
            os=new FileOutputStream(file);
            bos=new BufferedOutputStream(os);
            Streams.copy(bis, bos, true);
            k.setCompanyid(companyId);
            k.setCreateid(user.getCompanyUserId());
            k.setDeviceid(deviceid);
            k.setDevicetype(devicetype);
            k.setIndexnumber(indexnumber);
            k.setLastoperatorid(user.getCompanyUserId());
            k.setLinecode(linecode);
            k.setPhotoname(newFileName);
            k.setPhotosuffix(prefix);
            k.setPhototype(pictype);
            kService.add(k);
            resourcefile.delete();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }finally{
            if(bis!=null){
                try
                {
                    bis.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try
                {
                    os.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if(bos!=null){
                try{
                    bos.close(); 
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@RequestMapping("/addresourcepic")
@ResponseBody
public void addResoucePic(String picname){
    String resourcePath = "";
    String remotePath="";
    if(PwtzConstants.THE_SERVER_TYPE==1){
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
        remotePath=request.getSession().getServletContext().getRealPath("/")+"\\Attachment\\ResourcePIC\\";
    }else{
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
        resourcePath = resourcePath.replaceAll("\\\\", "/");    //本地
        remotePath=request.getSession().getServletContext().getRealPath("/")+"/Attachment/ResourcePIC/";
    }
//  resourcePath = resourcePath.replaceAll("\\\\", "/"); 
  
  try {
	picname=java.net.URLDecoder.decode(picname,"UTF-8");
} catch (UnsupportedEncodingException e1) {
}
  resourcePath=resourcePath+picname;
  FileInputStream is=null;
  FileOutputStream os=null;
  BufferedInputStream bis=null;
  BufferedOutputStream bos=null;
  File resourcefile=new File(resourcePath);
  if(!resourcefile.exists()){
      return;
  }
  File file=new File(remotePath);
  if(!file.exists()){
      file.mkdirs();
  }
  file=new File(remotePath+picname);
  try {
	is=new FileInputStream(resourcefile);

  bis=new BufferedInputStream(is);
  os=new FileOutputStream(file);
  bos=new BufferedOutputStream(os);
  Streams.copy(bis, bos, true);
  System.out.println("上传成功---------"+file.getAbsolutePath());
  resourcefile.delete();
  } catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
	e.printStackTrace();
}
}

@RequestMapping("/edite")
@ResponseBody
public void edite(String picname,String resourcepicname,String linecode,String devicename,String deviceid,String pid,int devicetype){
    CompanyUser user=(CompanyUser) request.getSession().getAttribute("user");
    Long companyId=user.getLastCompanyId();
    String prefix = "";
//    String fileName = "";
    String newFileName = "";
    String pictype = "";
    int indexnumber=0;
    String resourcePath = "";
    String remotePath="";
    if(PwtzConstants.THE_SERVER_TYPE==1){
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
        remotePath=request.getSession().getServletContext().getRealPath("/")+"\\Attachment\\"+companyId+"\\DevicePIC\\";
    }else{
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
        resourcePath = resourcePath.replaceAll("\\\\", "/");    //本地
        remotePath=request.getSession().getServletContext().getRealPath("/")+"/Attachment/"+companyId+"/DevicePIC/";
    }
    //String savePath="D:/upload/";
    //savePath = savePath.replaceAll("\\\\", "/");  //本地测试
    //resourcePath = resourcePath.replaceAll("/", "\\\\");    //服务器
//    resourcePath = resourcePath.replaceAll("\\\\", "/");    //本地测试
    try
    {
        if(pid.equals("")){
            Kzsxsbzp k=new Kzsxsbzp();
            picname=java.net.URLDecoder.decode(picname,"UTF-8");
            resourcePath=resourcePath+resourcepicname;
            prefix=resourcepicname.substring(resourcepicname.indexOf("."));
//            fileName=picname.substring(0,picname.indexOf("."));
            indexnumber=PwtzUtils.passInt(picname.substring(picname.length()-1));
            pictype=picname.substring(devicename.length(),picname.length()-1);
//            CompanyUser user=(CompanyUser) request.getSession().getAttribute("user");
//            Long companyId=user.getLastCompanyId();
//            remotePath=objMapper.selectByKey("DevicePICPath").get(0).getConfigValue();
//            remotePath=remotePath.replaceAll("@COMPANYID", companyId.toString());
            newFileName=picname+"_"+resourcepicname;
            FileInputStream is=null;
            FileOutputStream os=null;
            BufferedInputStream bis=null;
            BufferedOutputStream bos=null;
            File resourcefile=new File(resourcePath);
            if(!resourcefile.exists()){
                return;
            }
            File file=new File(remotePath);
            if(!file.exists()){
                file.mkdirs();
            }
            file=new File(remotePath+resourcepicname);
            try
            {
                is=new FileInputStream(resourcefile);
                bis=new BufferedInputStream(is);
                os=new FileOutputStream(file);
                bos=new BufferedOutputStream(os);
                Streams.copy(bis, bos, true);
                k.setCompanyid(companyId);
                k.setCreateid(user.getCompanyUserId());
                k.setDeviceid(deviceid);
                k.setDevicetype(devicetype);
                k.setIndexnumber(indexnumber);
                k.setLastoperatorid(user.getCompanyUserId());
                k.setLinecode(linecode);
                k.setPhotoname(newFileName);
                k.setPhotosuffix(prefix);
                k.setPhototype(pictype);
                kService.add(k);
                resourcefile.delete();
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (PwtzDatabaseException e)
            {
                e.printStackTrace();
            }finally{
                if(bis!=null){
                    try
                    {
                        bis.close();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                if(os!=null){
                    try
                    {
                        os.close();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                if(bos!=null){
                    try{
                        bos.close(); 
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }else{
            List<Kzsxsbzp> list=kService.selectDeviceByStatus(deviceid, 3);
            if(list!=null&&list.size()>0){
                for(Kzsxsbzp k: list){
                    if(k.getId().equals(pid)){
                        k.setPhotoname(picname+"_"+resourcepicname);
                        k.setStatus(1);
                        kService.update(k);
                        newklist.add(k);
                    }
                }
            }
        }    
    }
    catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
}

@RequestMapping("clean")
@ResponseBody
public void cleanpic(String picname){
    String piccommonpath = "";
    if(PwtzConstants.THE_SERVER_TYPE==1){
        piccommonpath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
    }else{
        piccommonpath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
        piccommonpath = piccommonpath.replaceAll("\\\\", "/");    //本地
    }
//  piccommonpath=piccommonpath.replaceAll("/", "\\\\");
//  piccommonpath=piccommonpath.replaceAll("\\\\", "/");//本地测试
  File file=new File(piccommonpath+picname);
  if(file.exists()){
      file.delete();
  }
}

@RequestMapping("delete")
@ResponseBody
public void deleteDifference(String deviceid){
    String picname="";
    File file;
    CompanyUser user=(CompanyUser) request.getSession().getAttribute("user");
    Long companyId=user.getLastCompanyId();
    String resourcePath="";
    if(PwtzConstants.THE_SERVER_TYPE==1){
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"\\Attachment\\"+companyId+"\\DevicePIC\\";
    }else{
        resourcePath=request.getSession().getServletContext().getRealPath("/")+"/Attachment/"+companyId+"/DevicePIC/";
    }
//  resourcePath=objMapper.selectByKey("DevicePICPath").get(0).getConfigValue();
//  resourcePath=remotePath.replaceAll("@COMPANYID", companyId.toString());
  //resourcePath = resourcePath.replaceAll("/", "\\\\");    //服务器
//    resourcePath = resourcePath.replaceAll("\\\\", "/");    //本地测试
    List<Kzsxsbzp> list=null;
    try
    {
        list=kService.selectDeviceByStatus(deviceid, 3);
        if(list!=null&&list.size()>0){
            for(Kzsxsbzp k : list){
                picname=k.getPhotoname().substring(k.getPhotoname().lastIndexOf("_")+1);
                file=new File(resourcePath+picname);
                if(file.exists()){
                    file.delete();
                }
                try
                {
                    kService.delete(k.getId());
                }
                catch (PwtzDatabaseException e)
                {
                    e.printStackTrace();
                }
                catch (CanNotDeleteException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    catch (PwtzDatabaseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
}

@RequestMapping(value="setStatus",method=RequestMethod.POST)
@ResponseBody
public void setStatus(String deviceid){
    List<Kzsxsbzp> list=null;
    try
    {
        list=kService.selectDeviceByStatus(deviceid, 1);
        if(list!=null&&list.size()>0){
            for(Kzsxsbzp k : list){
                k.setStatus(3);
                kService.update(k);
            }
        }
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
}

private void writeJsonObject(HttpServletRequest request, HttpServletResponse resp, String jsonData)
{
    System.out.println("jsonData="+jsonData);
    resp.setContentType("text/html;charset=utf-8");
    resp.setCharacterEncoding("utf-8");
    PrintWriter pw = null;
    try
    {
        pw = resp.getWriter();
        pw.print(jsonData);
        pw.flush();
    }
    catch (IOException e)
    {
        handleException(e);
    }
    finally
    {
        if (null != pw)
        {
            pw.close();
        }
    }
}
}
